package com.zhangxiaofanfan.hotcode.second;

import java.util.Stack;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:21:44
 */
public class HotCode031 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        // head.next = new ListNode(2);
        // head.next.next = new ListNode(3);
        // head.next.next.next = new ListNode(4);
        // head.next.next.next.next = new ListNode(5);
        HotCode031 hotCode = new HotCode031();
        hotCode.reverseKGroup(head, 2);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode header = new ListNode();
        header.next = head;
        ListNode before = header, after, temp;
        Stack<ListNode> stack = new Stack<>();
        while (true) {
            temp = before.next;
            for (int i = 0; i < k; i++) {
                if (temp == null) {
                    return header.next;
                }
                stack.push(temp);
                temp = temp.next;
            }
            after = temp;
            temp = before;
            while (!stack.isEmpty()) {
                temp.next = stack.pop();
                temp = temp.next;
            }
            temp.next = after;
            before = temp;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
